package com.liwen.service.task;

import com.liwen.service.task.model.TaskParam;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveTask;

/**
 * Created by xueyongfeng on 2018/3/21.
 */
public class MultiTablesListQueryTask<V> extends RecursiveTask<List<V>> {
    private static final long serialVersionUID = 2990022552051701483L;
    private int suffix;
    private int count;
    private TaskParam taskParam;

    private MultiTablesListQuery<V> func;


    public MultiTablesListQueryTask(int count, Integer suffix, TaskParam taskParam, MultiTablesListQuery func) {
        if (suffix != null) {
            this.suffix = suffix;
        }
        if (taskParam != null) {
            this.taskParam = taskParam;
        }

        this.func = func;
        this.count = count;

    }

    public List<V> query() {
        return func.query(suffix, taskParam);
    }



    @Override
    protected List<V> compute() {
        if (count > 0) {
            List<V> result = new ArrayList<>();
            List<MultiTablesListQueryTask> tasks = createChildTasks();
            for (MultiTablesListQueryTask task : tasks) {
                task.fork();
            }

            for (MultiTablesListQueryTask task : tasks) {
                Object taskResult = task.join();
                if (taskResult == null) {
                    continue;
                }
                result.addAll((List<V>) taskResult);
            }
            return result;
        } else {
            return query();
        }
    }

    private List<MultiTablesListQueryTask> createChildTasks() {
        List<MultiTablesListQueryTask> list = new ArrayList<>(count);
        for (int i = 0; i < count; i ++) {
            MultiTablesListQueryTask task = new MultiTablesListQueryTask(0, i, taskParam, func);
            list.add(task);
        }
        return list;
    }
}
